
package mblog.web.controller.admin;

import mblog.core.data.PMaterial;
import mblog.core.persist.service.MaterialService;
import mblog.web.controller.BaseController;
import mtons.modules.pojos.Paging;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author zhangyue
 * 2016-04-08
 */
@Controller("p_material_ctl")
@RequestMapping("/admin/material")
public class PMaterialController extends BaseController {

	@Autowired
	private MaterialService materialService;

	@RequestMapping("/list")
	public String list(Integer pn,String key,ModelMap model) {
		Paging page = wrapPage(pn);
		materialService.paging(page, key);
		model.put("page", page);
		model.put("key", key);

		return "/admin/material/list";
	}

	@RequestMapping("/delete")
	public String delete(Long id){
		materialService.delete(id);
		return "redirect:/admin/material/list";
	}

	@RequestMapping("/edit")
	public String edit(@RequestParam(value = "id",required = false,defaultValue = "0") long id, Model model) {
		if (id != 0) {
			PMaterial material = materialService.findById(id);
			model.addAttribute("material", material);
		}
		return "/admin/material/edit";
	}

	@RequestMapping("/save")
	public String save(@ModelAttribute(value = "material") PMaterial material,ModelMap model) {
		try {
			if(material.getId()>0){
				material.setUpdateTime(new Date());
				//如果是新增做一个校验
				List<PMaterial> list = materialService.getByNameAndModel(material.getName(),material.getModel());
				if(list!=null&&list.size()>0&&list.get(0).getId()-material.getId()!=0){
					model.put("message","该材料名称和规格已经存在");
					return null;
				}

			}else{

				//如果是新增做一个校验
				List<PMaterial> list = materialService.getByNameAndModel(material.getName(),material.getModel());
				if(list!=null&&list.size()>0){
					model.put("message","该材料名称和规格已经存在");
					return "/admin/material/edit";
				}
				material.setCreateTime(new Date());
				material.setUpdateTime(new Date());
			}
			material.setIsDel(0);
			materialService.save(material);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/admin/material/list";
	}
}